<?php
/**
 * 订单服务层
 * 处理订单创建、查询、更新等核心业务逻辑
 */
declare(strict_types=1);

namespace app\service;

use app\model\crm\Order;
use app\model\crm\LawsuitOrder;
use app\model\crm\LegalServiceOrder;
use app\model\crm\OrderPayment;
use app\model\crm\Customer;
use think\facade\Db;
use think\facade\Log;
use think\Exception;

class OrderService
{
    /**
     * 创建订单
     * @param array $data 订单数据
     * @param int $userId 当前用户ID
     * @return array
     * @throws Exception
     */
    public function createOrder(array $data, int $userId): array
    {
        Db::startTrans();
        try {
            // 1. 获取客户信息
            $customer = Customer::find($data['customer_id']);
            if (!$customer) {
                throw new Exception('客户不存在');
            }
            
            // 2. 生成订单编号
            $orderNo = Order::generateOrderNo();
            
            // 3. 准备订单主记录数据
            $orderData = [
                'order_no'                => $orderNo,
                'customer_id'             => $data['customer_id'],
                'customer_name'           => $customer->name,
                'customer_type'           => $data['customer_type'],
                'id_number'               => $data['id_number'] ?? '',
                'contact_id'              => $data['contact_id'] ?? null,
                'contact_name'            => $data['contact_name'] ?? '',
                'contact_phone'           => $data['contact_phone'] ?? '',
                'order_category'          => $data['order_category'],
                'order_type'              => $data['order_type'],
                'contract_no'             => $data['contract_no'] ?? '',
                'contract_amount'         => $data['contract_amount'] ?? 0,
                'post_amount'             => $data['post_amount'] ?? 0,
                'total_amount'            => ($data['contract_amount'] ?? 0) + ($data['post_amount'] ?? 0),
                'paid_amount'             => 0,
                'signer_id'               => $userId,
                'signer_name'             => $data['signer_name'] ?? '',
                'contract_start_date'     => $data['contract_start_date'] ?? null,
                'contract_end_date'       => $data['contract_end_date'] ?? null,
                'contract_sign_date'      => $data['contract_sign_date'] ?? null,
                'contract_files'          => $data['contract_files'] ?? null,
                'payment_status'          => Order::PAYMENT_STATUS_UNPAID,
                'contract_archive_status' => 0,
                'approval_status'         => Order::APPROVAL_STATUS_PENDING,
                'delivery_status'         => Order::DELIVERY_STATUS_PENDING,
                'department_id'           => $data['department_id'] ?? 0,
                'remark'                  => $data['remark'] ?? '',
            ];
            
            // 4. 创建订单主记录
            $order = Order::create($orderData);
            
            // 5. 根据订单大类创建详情记录
            if ($data['order_category'] == Order::CATEGORY_LAWSUIT) {
                // 诉讼订单详情
                $this->createLawsuitOrderDetail($order->id, $data['lawsuit_detail'] ?? []);
            } elseif ($data['order_category'] == Order::CATEGORY_LEGAL_SERVICE) {
                // 非诉订单详情
                $this->createLegalServiceOrderDetail($order->id, $data['legal_service_detail'] ?? []);
            }
            
            // 6. 创建支付记录
            if (!empty($data['payment_records'])) {
                $totalPaid = $this->createPaymentRecords($order->id, $data['payment_records']);
                
                // 更新订单已支付金额和支付状态
                $order->paid_amount = $totalPaid;
                $order->payment_status = $this->calculatePaymentStatus($totalPaid, $order->total_amount);
                $order->save();
            }
            
            // 7. 创建工作流审批实例（如果配置了审批流程）
            if (config('workflow.crm_order_approval_enabled', true)) {
                $approvalId = $this->createApprovalInstance($order, $userId);
                $order->approval_id = $approvalId;
                $order->approval_status = Order::APPROVAL_STATUS_PROCESSING;
                $order->save();
            }
            
            Db::commit();
            
            return [
                'order_id'        => $order->id,
                'order_no'        => $order->order_no,
                'approval_id'     => $order->approval_id ?? 0,
                'approval_status' => $order->approval_status,
            ];
            
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('订单创建失败: ' . $e->getMessage(), [
                'data'   => $data,
                'userId' => $userId,
                'trace'  => $e->getTraceAsString(),
            ]);
            throw $e;
        }
    }
    
    /**
     * 创建诉讼订单详情
     */
    private function createLawsuitOrderDetail(int $orderId, array $data): void
    {
        $detailData = [
            'order_id'                    => $orderId,
            'lawsuit_type'                => $data['lawsuit_type'] ?? 1,
            'is_member_customer'          => $data['is_member_customer'] ?? 0,
            'is_first_experience'         => $data['is_first_experience'] ?? 0,
            'entrusting_party_identity'   => $data['entrusting_party_identity'] ?? 1,
            'opposing_party_type'         => $data['opposing_party_type'] ?? 2,
            'opposing_party_name'         => $data['opposing_party_name'] ?? '',
            'case_cause_id'               => $data['case_cause_id'] ?? null,
            'case_cause_name'             => $data['case_cause_name'] ?? '',
            'litigation_stage_category'   => $data['litigation_stage_category'] ?? 1,
            'civil_stages'                => $data['civil_stages'] ?? null,
            'criminal_stages'             => $data['criminal_stages'] ?? null,
            'case_amount_range'           => $data['case_amount_range'] ?? 1,
            'case_amount_exact'           => $data['case_amount_exact'] ?? null,
            'litigation_request_elements' => $data['litigation_request_elements'] ?? null,
            'main_litigation_request'     => $data['main_litigation_request'] ?? '',
            'service_fee_pre'             => $data['service_fee_pre'] ?? 0,
            'service_fee_post'            => $data['service_fee_post'] ?? 0,
        ];
        
        LawsuitOrder::create($detailData);
    }
    
    /**
     * 创建非诉订单详情
     */
    private function createLegalServiceOrderDetail(int $orderId, array $data): void
    {
        $detailData = [
            'order_id'                 => $orderId,
            'service_category'         => $data['service_category'] ?? 1,
            'package_type'             => $data['package_type'] ?? null,
            'is_new_member'            => $data['is_new_member'] ?? 0,
            'account_type'             => $data['account_type'] ?? null,
            'main_account_customer_id' => $data['main_account_customer_id'] ?? null,
            'sub_account_owner_type'   => $data['sub_account_owner_type'] ?? null,
            'has_first_experience'     => $data['has_first_experience'] ?? 0,
            'lawsuit_guidance_quota'   => $data['lawsuit_guidance_quota'] ?? 0,
            'lawsuit_guidance_used'    => 0,
            'debt_collection_quota'    => $data['debt_collection_quota'] ?? 0,
            'debt_collection_used'     => 0,
            'service_items'            => $data['service_items'] ?? null,
            'special_service_types'    => $data['special_service_types'] ?? null,
            'service_fee'              => $data['service_fee'] ?? 0,
            'service_start_date'       => $data['service_start_date'] ?? null,
            'service_end_date'         => $data['service_end_date'] ?? null,
        ];
        
        LegalServiceOrder::create($detailData);
    }
    
    /**
     * 创建支付记录
     */
    private function createPaymentRecords(int $orderId, array $records): float
    {
        $totalPaid = 0;
        
        foreach ($records as $record) {
            $paymentData = [
                'order_id'             => $orderId,
                'payment_item'         => $record['payment_item'] ?? 1,
                'payment_amount'       => $record['payment_amount'] ?? 0,
                'payment_method'       => $record['payment_method'] ?? 1,
                'payment_date'         => $record['payment_date'] ?? time(),
                'payment_proof_files'  => $record['payment_proof_files'] ?? null,
                'payer_name'           => $record['payer_name'] ?? '',
                'receiver_account'     => $record['receiver_account'] ?? '',
                'verification_status'  => OrderPayment::VERIFICATION_PENDING,
                'remark'               => $record['remark'] ?? '',
            ];
            
            OrderPayment::create($paymentData);
            $totalPaid += $paymentData['payment_amount'];
        }
        
        return $totalPaid;
    }
    
    /**
     * 计算支付状态
     */
    private function calculatePaymentStatus(float $paidAmount, float $totalAmount): int
    {
        if ($paidAmount <= 0) {
            return Order::PAYMENT_STATUS_UNPAID;
        }
        
        if ($paidAmount >= $totalAmount) {
            return Order::PAYMENT_STATUS_PAID;
        }
        
        return Order::PAYMENT_STATUS_PARTIAL;
    }
    
    /**
     * 创建工作流审批实例
     */
    private function createApprovalInstance(Order $order, int $userId): int
    {
        // TODO: 调用WorkflowService创建审批实例
        // 这里需要根据实际的工作流服务接口实现
        
        // 暂时返回0，实际应该返回审批ID
        return 0;
    }
    
    /**
     * 获取订单列表
     */
    public function getOrderList(array $params, int $userId, string $dataPermission = 'own'): array
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        
        $query = Order::with(['orderType']);
        
        // 数据权限过滤
        if ($dataPermission === 'own') {
            $query->where('signer_id', $userId);
        } elseif ($dataPermission === 'department') {
            // TODO: 根据部门过滤
        }
        
        // 搜索条件
        if (!empty($params['order_no'])) {
            $query->where('order_no', 'like', '%' . $params['order_no'] . '%');
        }
        
        if (!empty($params['customer_name'])) {
            $query->where('customer_name', 'like', '%' . $params['customer_name'] . '%');
        }
        
        if (isset($params['order_category'])) {
            $query->where('order_category', $params['order_category']);
        }
        
        if (isset($params['order_type'])) {
            $query->where('order_type', $params['order_type']);
        }
        
        if (isset($params['approval_status'])) {
            $query->where('approval_status', $params['approval_status']);
        }
        
        if (isset($params['payment_status'])) {
            $query->where('payment_status', $params['payment_status']);
        }
        
        if (!empty($params['start_date']) && !empty($params['end_date'])) {
            $query->whereBetweenTime('create_time', $params['start_date'], $params['end_date']);
        }
        
        // 排序
        $query->order('create_time', 'desc');
        
        // 分页查询
        $result = $query->paginate([
            'list_rows' => $limit,
            'page'      => $page,
        ]);
        
        return [
            'list'  => $result->items(),
            'total' => $result->total(),
            'page'  => $page,
            'limit' => $limit,
        ];
    }
    
    /**
     * 获取订单详情
     */
    public function getOrderDetail(int $orderId, int $userId): array
    {
        $order = Order::with([
            'lawsuitOrder',
            'legalServiceOrder',
            'payments',
            'orderType',
            'customer',
            'contact',
        ])->find($orderId);
        
        if (!$order) {
            throw new Exception('订单不存在');
        }
        
        // TODO: 数据权限验证
        
        return $order->toArray();
    }
    
    /**
     * 新增支付记录
     */
    public function addPaymentRecord(int $orderId, array $data, int $userId): array
    {
        Db::startTrans();
        try {
            $order = Order::find($orderId);
            if (!$order) {
                throw new Exception('订单不存在');
            }
            
            // 创建支付记录
            $payment = OrderPayment::create([
                'order_id'            => $orderId,
                'payment_item'        => $data['payment_item'],
                'payment_amount'      => $data['payment_amount'],
                'payment_method'      => $data['payment_method'],
                'payment_date'        => $data['payment_date'] ?? time(),
                'payment_proof_files' => $data['payment_proof_files'] ?? null,
                'payer_name'          => $data['payer_name'] ?? '',
                'receiver_account'    => $data['receiver_account'] ?? '',
                'remark'              => $data['remark'] ?? '',
            ]);
            
            // 更新订单已支付金额和支付状态
            $totalPaid = OrderPayment::where('order_id', $orderId)
                ->where('delete_time', 0)
                ->sum('payment_amount');
            
            $order->paid_amount = $totalPaid;
            $order->payment_status = $this->calculatePaymentStatus($totalPaid, $order->total_amount);
            $order->save();
            
            Db::commit();
            
            return [
                'payment_id'        => $payment->id,
                'order_paid_amount' => $order->paid_amount,
                'payment_status'    => $order->payment_status,
            ];
            
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('添加支付记录失败: ' . $e->getMessage());
            throw $e;
        }
    }
}
